<?php
// No direct access
defined( '_JEXEC' ) or die( 'Restricted access' );

jimport( 'joomla.application.component.model' );
//jimport('joomla.filesystem.file');


class ModelImages extends JModel {

    /*
    private $hostname = "localhost";
    private $username = "sp3ctrum";
    private $password = "";
    private $db_name = "my_sp3ctrum";
    */

    private $hostname = "localhost";
    private $username = "root";
    private $password = "root";
    private $db_name = "gnu";

    /*
    private $hostname = "62.149.150.87";
    private $username = "Sql322031";
    private $password = "0a68934c";
    private $db_name = "Sql322031_5";
    */


    private $active = false;
    private $link;

    public function connect() {
        if(!$this->active) {
            $this->link = mysql_connect($this->hostname,$this->username,$this->password);
        }else {
            return true;
        }
    }

    public function disconnect() {
        if($this->active) {
            mysql_close();
            $this->active = false;
        }
    }

    public function insertImage($lat,$lon,$name,$path,$icon) {
        if(!$this->active) {
            $this->connect();
        }
        $db_selected = mysql_select_db($this->db_name, $this->link);
        if (!$db_selected) {
            die ('Can\'t use foo : ' . mysql_error());
        }
        $query = "INSERT INTO images VALUES('','$lat','$lon','$name','$path','$icon')";
        //echo $query;
        $sql = mysql_query($query) or die (mysql_error());
        return $sql;
    }

    public function retrieveImagesCount() {
        if(!$this->active) {
            $this->connect();
        }
        $db_selected = mysql_select_db($this->db_name, $this->link);
        if (!$db_selected) {
            die ("Errore nella selezione del db: " . mysql_error());
        }
        $query = "SELECT * FROM images";
        $result = mysql_query($query);

        return mysql_numrows($result);
    }

    public function retrieveMarkers() {
        if(!$this->active) {
            $this->connect();
        }
        $db_selected = mysql_select_db($this->db_name, $this->link);
        if (!$db_selected) {
            die ("Errore nella selezione del db: " . mysql_error());
        }
        $query = "SELECT * FROM images";
        $result = mysql_query($query);
        //init array to store marker informations
        $markers;

        if(mysql_numrows($result) > 0) {
            $i=0;
            while ($i < mysql_numrows($result)) {
                $marker = array("latitude"=>mysql_result($result,$i,"latitude"),
                    "longitude"=>mysql_result($result,$i,"longitude"),
                    "name"=>mysql_result($result,$i,"name"),
                    "filepath"=>mysql_result($result,$i,"filepath"),
                    "icon"=>mysql_result($result,$i,"icon"));

                $markers[$i] = $marker;
                $i++;
            }
        }

        return $markers;
    }

    public function checkImagePath($filepath) {

        if(file_exists($filepath)) { //This function returns FALSE for files inaccessible due to safe mode restrictions.

            $str_split = explode(".",$filepath);
            $extension = $str_split[count($str_split)-1];
            if($extension == "jpg" || $extension == "JPG" || $extension == "jpeg" || $extension == "JPEG") {
                echo "$extension";
                return true;
            }
        }
        return false;
    }

    // TODO: test me !
    public function getImageLocation($imageFile) {

        $tag_array = exif_read_data($imageFile, 'EXIF');

        $lon;$lat;

        if(count($tag_array["GPSLongitude"]) > 0) {
            $lon = $this->convertToHemi($tag_array["GPSLongitude"], $tag_array['GPSLongitudeRef']);
            $lat = $this->convertToHemi($tag_array["GPSLatitude"], $tag_array['GPSLatitudeRef']);
        }
        
        return array("latitude" => $lat, "longitude" => $lon);

    }

    public function uploadFile($max, $dest_dir, $file_type, $msg) {

        $file = JRequest::getVar('file_upload', null, 'files', 'array');
        // Array ( [name] => mod_simpleupload_1.2.1.zip [type] => application/zip [tmp_name] => /tmp/phpo3VG9F [error] => 0 [size] => 4463 )

        if(isset($file)) {

            $filename = JFile::makeSafe($file['name']);

            if($file['size'] > $max) $msg = JText::_('ONLY_FILES_UNDER').' '.$max;

            $src = $file['tmp_name'];
            $dest = $dest_dir . DS . $filename;

            //First check if the file has the right extension, we need jpg only
            if ($file['type'] == $file_type || $file_type == '*') {
                if ( JFile::upload($src, $dest) ) {

                //Redirect to a page of your choice
                    $msg = JText::_('FILE_SAVE_AS').' '.$dest;
                } else {
                //Redirect and throw an error message
                    $msg = JText::_('ERROR_IN_UPLOAD');
                }
            } else {
            //Redirect and notify user file is not right extension
                $msg = JText::_('FILE_TYPE_INVALID');
            }

        //$msg = "<script>alert('". $msg ."');</script>";
        }
        return $msg;
    }

    function convertToHemi($exifCoord, $hemi) {

        $degrees = count($exifCoord) > 0 ? $this->gps2Num($exifCoord[0]) : 0;
        $minutes = count($exifCoord) > 1 ? $this->gps2Num($exifCoord[1]) : 0;
        $seconds = count($exifCoord) > 2 ? $this->gps2Num($exifCoord[2]) : 0;

        $flip = ($hemi == 'W' or $hemi == 'S') ? -1 : 1;

        return $flip * ($degrees + $minutes / 60);

    }

    function gps2Num($coordPart) {

        $parts = explode('/', $coordPart);

        if (count($parts) <= 0)
            return 0;

        if (count($parts) == 1)
            return $parts[0];

        return floatval($parts[0]) / floatval($parts[1]);
    }

}
?>
